package com.zbest.component.dal.sequence;

import java.util.concurrent.atomic.AtomicLong;

/**
 * sequence范围对象，通过内存来实现sequence
 *
 * @author czhou3306
 * @version $Id: SequenceRange.java, v 0.1 2014-11-30 下午5:24:25 czhou3306 Exp $
 */
public class SequenceRange {
    private final long min;
    private final long max;

    private final AtomicLong value;

    private volatile boolean over = false;

    public SequenceRange(long min, long max) {
        this.min = min;
        this.max = max;
        this.value = new AtomicLong(min);
    }

    public long getAndAdd(long delta) {
        long currentValue = value.getAndAdd(delta);
        if (currentValue > max || currentValue + delta - 1 > max) {
            over = true;
            return -1;
        }

        return currentValue;
    }

    public long getMin() {
        return min;
    }

    public long getMax() {
        return max;
    }

    public boolean isOver() {
        return over;
    }

    @Override
    public String toString() {
        return "SequenceRange [max=" + max + ", min=" + min + ", over=" + over + ", value="
                + value.get() + "]";
    }
}
